package com.attcatstudy.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

/**
 * @author attcat
 * ---做一个有趣的程序员
 * @date 2022-11-01 22:09
 * @description
 */
@Slf4j
public class ABATest {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(1);

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        int value = atomicInteger.get();
                        log.info("Thread1 read value!"+value);
                        //// 阻塞1s
//                        LockSupport.parkNanos(1000000000L);
                        if (atomicInteger.compareAndSet(value, 3)){
                            log.info("Thread1 update value!"+atomicInteger.get());
                        }else {
                            log.info("Thread1 update fail!");
                        }
                    }
                }
        ,"Thread1").start();


        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        int value = atomicInteger.get();
                        log.debug("Thread2 read value: " + value);
                        int value2 = atomicInteger.get();
                        log.debug("Thread2 read value2: " + value2);
                        if (atomicInteger.compareAndSet(value, 2)){
                            log.info("Thread2 update value!"+atomicInteger.get());

                        }else {
                            log.info("Threa2 update fail!");
                        }

                        value = atomicInteger.get();
                        log.debug("Thread2 read value: " + value);
                        if (atomicInteger.compareAndSet(value, 10)){
                            log.info("Thread2 update value!"+atomicInteger.get());

                        }else {
                            log.info("Threa2 update fail!");
                        }
                    }
                }
                ,"Threa2").start();









    }




}
